﻿///***************************************************************
/// 시  스  템 : Updms.Fit
/// 단위시스템 : FIT
/// 계      층 : Presentation Layer
/// 프로그램명 : Fit1011m
/// 파  일  명 : Fit1011m.aspx.cs
/// 설      명 : 트레이닝관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2014-05-21 송시명   최초 작성
///***************************************************************
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Com.Exe;
using Updms.Fit.Exe;

namespace Updms.Fit
{
	public partial class Fit1011m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		public static readonly string PID = "Fit1011m";
		public static readonly string gs_path_info = "/updms/Fit/" + PID + ".aspx";

		Global global = new Global();
		AccessCheck access = new AccessCheck();
		CommCode.Com com = new CommCode.Com(LANG_SET);
		CommCode.Fit fit = new CommCode.Fit(LANG_SET);

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = 10;//GRID_PAGESIZE;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	//운동일(시작)
		protected string kw2 = "";	//운동일(종료)
		protected string kw3 = "";	//운동부위
		protected string kw4 = "";	//운동명
		protected string kw5 = "";	//장소

		//메뉴 선택값
		protected string gs_sm = "";

		//페이지모드
		private string gs_page_mode = "";	// 팝업으로 열지 여부
		private string gs_training_dt = "";	//운동일

		//페이지별합계
		decimal ld_total_weight = 0;
		decimal ld_total_count = 0;
		decimal ld_total_set = 0;

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
			SetClientScriptNoPostBack();
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetSearchTrainingPart();
			SetSearchTrainingType();
			SetNewTrainingId();
			SetTrainingTime();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript, SetClientScriptNoPostBack

		private void SetClientScript()
		{
			//onKeyPress이벤트 (엔터검색)
			txt_search_training_dt_from.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_training_dt_to.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_location.Attributes.Add("onkeypress", "enterSearchOnPage(event)");

			//달력콘트롤 설정
			ce_training_dt.SelectedDate = DateTime.Now.AddDays(0);
		}

		//포스트백과 무관하게 이벤트 지정
		private void SetClientScriptNoPostBack()
		{
			cbl_search_training_part.Items[0].Attributes.Add("onclick", "checkBoxListCheck('cbl_search_training_part');");
			cbl_search_training_type.Items[0].Attributes.Add("onclick", "checkBoxListCheck('cbl_search_training_type');");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
			gs_page_mode = string.IsNullOrEmpty(Request.QueryString["page_mode"]) ? "" : Request.QueryString["page_mode"].ToString();
			gs_training_dt = string.IsNullOrEmpty(Request.QueryString["training_dt"]) ? "" : Request.QueryString["training_dt"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))
					{
						if (String.IsNullOrEmpty(txt_search_training_dt_from.Text))
						{
							kw1 = DateUtil.GetMonthEx(-1); //한달전
							txt_search_training_dt_from.Text = kw1;
						}
						else
						{
							kw1 = txt_search_training_dt_from.Text.Trim();
						}
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						txt_search_training_dt_from.Text = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))
					{
						if (String.IsNullOrEmpty(txt_search_training_dt_to.Text))
						{
							kw2 = DateUtil.GetLastMonthDay(DateUtil.GetMonthEx(0, "yyyy-MM")); //당월의 마지막일
							txt_search_training_dt_to.Text = kw2;
						}
						else
						{
							kw2 = txt_search_training_dt_to.Text.Trim();
						}
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						txt_search_training_dt_to.Text = kw2;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))
					{
						kw3 = WebControlUtil.GetCheckBoxListValue(cbl_search_training_part, 1);
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						WebControlUtil.SetCheckBoxListValue(cbl_search_training_part, kw3);
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))
					{
						kw4 = WebControlUtil.GetCheckBoxListValue(cbl_search_training_type, 1);
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						WebControlUtil.SetCheckBoxListValue(cbl_search_training_type, kw4);
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw5"]))
					{
						kw5 = txt_search_location.Text.Trim();
					}
					else
					{
						kw5 = Server.UrlDecode(Request.QueryString["kw5"]);
						txt_search_location.Text = kw5;
					}

					break;
				case "SEARCH":
					kw1 = String.IsNullOrEmpty(txt_search_training_dt_from.Text) ? DateUtil.GetMonthEx(-1) : txt_search_training_dt_from.Text.Trim();
					kw2 = String.IsNullOrEmpty(txt_search_training_dt_to.Text) ? DateUtil.GetLastMonthDay(DateUtil.GetMonthEx(0, "yyyy-MM")) : txt_search_training_dt_to.Text.Trim();
					kw3 = WebControlUtil.GetCheckBoxListValue(cbl_search_training_part, 1);
					kw4 = WebControlUtil.GetCheckBoxListValue(cbl_search_training_type, 1);
					kw5 = txt_search_location.Text.Trim();
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw3 = WebControlUtil.GetCheckBoxListText(cbl_search_training_part, 1);
			string ls_kw4 = WebControlUtil.GetCheckBoxListText(cbl_search_training_type, 1);
			lbl_search_keyword.Text = kw1 + " ~ " + kw2 + " / " + ls_kw3 + " / " + ls_kw4 + " / " + kw5;
		}

		#endregion

		#region 마스터 Method (SetSearchTrainingPart, SetTrainingTypeNm)

		private void SetSearchTrainingPart()
		{
			fit.SetTrainingPart(cbl_search_training_part);
			fit.SetTrainingPart(cbl_training_part);

			cbl_search_training_part.Items.Insert(0, new ListItem(GetXmlMsg("STR_019"), "ALL"));	//전체선택
		}

		private void SetSearchTrainingType()
		{
			DataSet lo_ds = new DataSet();
			Fit1010m_NT _Fit1010m_NT = new Fit1010m_NT();

			lo_ds.Merge(_Fit1010m_NT.GetTrainingType());

			cbl_search_training_type.Items.Clear();
			cbl_search_training_type.DataSource = lo_ds;
			cbl_search_training_type.DataMember = "UPDMS_FIT_TRAINING_TYPE";
			cbl_search_training_type.DataTextField = "Training_Nm";
			cbl_search_training_type.DataValueField = "Training_Type_Id";
			cbl_search_training_type.DataBind();

			cbl_search_training_type.Items.Insert(0, new ListItem(GetXmlMsg("STR_019"), "ALL"));	//전체선택
		}

		#endregion

		#region 디테일 Method (SetNewTrainingId, SetTrainingTime, SetTrainingPart, SetCalcTotalTrainingResult, SetTrainingPartHeight, SetChangeBtn, SetExtendRemark)

		//신규 운동ID
		private void SetNewTrainingId()
		{
			lbl_training_id.Text = global.GetNewIdByTable("UPDMS_FIT_WEIGHT_TRAINING", "Training_Id", "TR", "8");
		}

		//시간정보
		private void SetTrainingTime()
		{
			com.SetTimeHour(ddl_start_hour);
			com.SetTimeHour(ddl_end_hour);
			com.SetTimeMinute(ddl_start_minute);
			com.SetTimeMinute(ddl_end_minute);
		}

		//운동종류 설정
		private void SetTrainingPart(string training_id)
		{
			SelectPartsProcess(training_id, WebControlUtil.GetCheckBoxListValue(cbl_training_part));
		}

		//운동결과 합계
		private void SetCalcTotalTrainingResult()
		{
			decimal ld_calc_action_weight = 0;
			decimal ld_calc_action_count = 0;
			decimal ld_calc_set_count = 0;

			//선택한 Row의 중량,반복횟수,세트를 계산한다.
			for (int i = 0; i < gv_parts.Rows.Count; i++)
			{
				CheckBox cb_select = (CheckBox)gv_parts.Rows[i].FindControl("cb_select");
				TextBox txt_action_weight = (TextBox)gv_parts.Rows[i].FindControl("txt_action_weight");
				TextBox txt_action_count = (TextBox)gv_parts.Rows[i].FindControl("txt_action_count");
				TextBox txt_set_count = (TextBox)gv_parts.Rows[i].FindControl("txt_set_count");
				decimal ld_weight_calc_rate = Convert.ToDecimal(gv_parts.DataKeys[i].Values["Weight_Calc_Rate"].ToString());

				if (cb_select.Checked)
				{
					decimal ld_checked_action_weight = 0;
					decimal ld_checked_action_count = 0;
					decimal ld_checked_set_count = 0;

					ld_checked_action_weight = Convert.ToDecimal(ConversionUtil.DefaultValue(txt_action_weight.Text.Trim(), "0"));
					ld_checked_action_count = Convert.ToDecimal(ConversionUtil.DefaultValue(txt_action_count.Text.Trim(), "0"));
					ld_checked_set_count = Convert.ToDecimal(ConversionUtil.DefaultValue(txt_set_count.Text.Trim(), "0"));

					ld_calc_action_weight += ld_checked_action_weight * ld_checked_action_count * ld_weight_calc_rate * ld_checked_set_count;
					ld_calc_action_count += ld_checked_action_count * ld_checked_set_count;
					ld_calc_set_count += ld_checked_set_count;
				}
			}

			ltr_calc_action_weight.Text = ld_calc_action_weight.ToString("#,###,##0");
			ltr_calc_action_count.Text = ld_calc_action_count.ToString("#,###,##0");
			ltr_calc_set_count.Text = ld_calc_set_count.ToString("#,###,##0");
		}

		//운동결과영역 높이지정
		private void SetTrainingPartHeight()
		{
			div_detail_2.Attributes.CssStyle.Remove("height");

			if (cb_part_list_all.Checked)
			{
				int h = (gv_parts.Rows.Count * 23) + 1; //전체 row수 * 하나의 row높이 + 1px
				div_detail_2.Attributes.CssStyle.Add("height", h.ToString() + "px");
			}
			else
			{
				div_detail_2.Attributes.CssStyle.Add("height", "230px"); //div_detail_2의 높이와 같게한다
			}
		}

		//변경버튼 활성화
		private void SetChangeBtn()
		{
			ibtn_move.Visible = access.CheckPgmUsingGrant(USER_DIV, PID);
		}

		//비고높이 재설정(운동결과 체크박스 클릭시 PostBack후)
		private void SetExtendRemark()
		{
			for (int i = 0; i < gv_parts.Rows.Count; i++)
			{
				CheckBox cb_select = (CheckBox)gv_parts.Rows[i].FindControl("cb_select");
				TextBox txt_remark = (TextBox)gv_parts.Rows[i].FindControl("txt_remark");
				CheckBox cb_remark = (CheckBox)gv_parts.Rows[i].FindControl("cb_remark");

				//S와 비고가 모두 체크되어 있으면 비고의 높이를 80px로 한다
				if (cb_select.Checked && cb_remark.Checked)
				{
					txt_remark.Height = 80;
				}
				else
				{
					txt_remark.Height = 12;
				}
			}
		}

		#endregion

		#region CRUD 운동결과 (SelectPartsProcess, InsertPartsProcess)

		//조회 - training_id를 안넘기면 운동종류만 조회해온다
		private void SelectPartsProcess(string training_id, string training_part)
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_training_id", typeof(string), training_id);
			lo_dp.AddProperty("ls_training_part", typeof(string), training_part);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Fit1011m_NT _Fit1011m_NT = new Fit1011m_NT())
			{
				lo_ds.Merge(_Fit1011m_NT.GetSavedTypeList(lo_dp));
			}

			//일단 바인딩
			gv_parts.DataSource = lo_ds;
			gv_parts.DataBind();

			for (int i = 0; i < DataSetUtil.GetRowCount(lo_ds, "UPDMS_FIT_WEIGHT_TRAINING_PARTS"); i++)
			{
				string ls_save_yn = DataSetUtil.GetFldStr(lo_ds, "UPDMS_FIT_WEIGHT_TRAINING_PARTS", i, "Save_Yn");
				
				CheckBox cb_select = (CheckBox)gv_parts.Rows[i].FindControl("cb_select");
				TextBox txt_action_weight = (TextBox)gv_parts.Rows[i].FindControl("txt_action_weight");
				TextBox txt_action_count = (TextBox)gv_parts.Rows[i].FindControl("txt_action_count");
				TextBox txt_set_count = (TextBox)gv_parts.Rows[i].FindControl("txt_set_count");
				TextBox txt_remark = (TextBox)gv_parts.Rows[i].FindControl("txt_remark");
				CheckBox cb_remark = (CheckBox)gv_parts.Rows[i].FindControl("cb_remark");

				//저장된 데이터이면 체크함
				if (ls_save_yn == "Y")
				{
					cb_select.Checked = true;
					txt_action_weight.Enabled = true;
					txt_action_count.Enabled = true;
					txt_set_count.Enabled = true;
					txt_remark.Enabled = true;
					cb_remark.Enabled = true;

					//어트리뷰트 추가
					string ls_attr_action_weight = "document.form1." + txt_action_weight.UniqueID + ".value=extractNumberDot(document.form1." + txt_action_weight.UniqueID + ".value);";
					string ls_attr_action_count = "document.form1." + txt_action_count.UniqueID + ".value=extractNumber(document.form1." + txt_action_count.UniqueID + ".value);";
					string ls_attr_set_count = "document.form1." + txt_set_count.UniqueID + ".value=extractNumber(document.form1." + txt_set_count.UniqueID + ".value);";
					txt_action_weight.Attributes.Add("onkeyup", ls_attr_action_weight);
					txt_action_count.Attributes.Add("onkeyup", ls_attr_action_count);
					txt_set_count.Attributes.Add("onkeyup", ls_attr_set_count);
					cb_remark.Attributes.Add("onclick", "extendRemark(\"" + txt_remark.ClientID + "\", \"" + cb_remark.ClientID + "\");");

					//td를 돌면서 class 추가
					for (int j = 0; j < gv_parts.Rows[i].Cells.Count; j++)
					{
						gv_parts.Rows[i].Cells[j].Attributes.Add("class", "bg_white");
					}
				}
				else
				{
					cb_select.Checked = false;
					txt_action_weight.Text = "";
					txt_action_count.Text = "";
					txt_set_count.Text = "";
					txt_remark.Text = "";

					txt_action_weight.Enabled = false;
					txt_action_count.Enabled = false;
					txt_set_count.Enabled = false;
					txt_remark.Enabled = false;
					cb_remark.Enabled = false;
					cb_remark.Checked = false;

					//td를 돌면서 class 추가
					for (int j = 0; j < gv_parts.Rows[i].Cells.Count; j++)
					{
						gv_parts.Rows[i].Cells[j].Attributes.Add("class", "bg_gray");
					}
				}
			}

			//체크박스리스트 선택처리
			WebControlUtil.SetCheckBoxListValue(cbl_training_part, training_part);
		}

		//저장
		private void InsertPartsProcess()
		{
			using (Fit1011m_RT _Fit1011m_RT = new Fit1011m_RT())
			{
				int li_return = _Fit1011m_RT.InsertPartsProcess(lbl_training_id.Text, SetValueParts());
			}
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_training_dt_from", typeof(string), kw1);
			lo_dp.AddProperty("ls_training_dt_to", typeof(string), kw2);
			lo_dp.AddProperty("ls_training_part", typeof(string), kw3);
			lo_dp.AddProperty("ls_training_type_id", typeof(string), kw4);
			lo_dp.AddProperty("ls_location", typeof(string), kw5);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Fit1011m_NT _Fit1011m_NT = new Fit1011m_NT())
			{
				li_row_count = _Fit1011m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Fit1011m_NT.SelectProcess(lo_dp));

				GridView1.DataSource = lo_ds;
				GridView1.DataBind();

				string search_condition = "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&kw4=" + Server.UrlEncode(kw4) + "&kw5=" + Server.UrlEncode(kw5) + "&page_mode=" + gs_page_mode + "&training_dt=" + gs_training_dt + "&page=";

				Pager pager = new Pager(this, ref lbl_page);
				pager.PageNavigation(
					li_cur_page,
					li_page_count,
					gs_path_info + search_condition);

				//결과출력(키워드, 검색행수)
				ShowKeywordLabel();
				lbl_result_count.Text = li_row_count.ToString("#,###,##0");

				//즐겨찾기
				ibtn_favorite.Attributes.Add("onclick", "javascript:goFavoriteSearchPage('" + PID + "','" + search_condition + "');return false;");
			}
		}

		//저장
		private void InsertProcess()
		{
			using (Fit1011m_RT _Fit1011m_RT = new Fit1011m_RT())
			{
				int li_return = _Fit1011m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				
				if (gs_page_mode == "P")
				{
					string ls_msg_tp = (li_return > 0) ? "ICR" : "AC";
					CallMsgBoxInAjax(ls_msg_id, null, ls_msg_tp);
				}
				else
				{
					CallMsgBoxInAjax(ls_msg_id);
				}

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Fit1011m_RT _Fit1011m_RT = new Fit1011m_RT())
			{
				int li_return = _Fit1011m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Fit1011m_RT _Fit1011m_RT = new Fit1011m_RT())
			{
				int li_return = _Fit1011m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
			SelectPartsProcess("", "");
		}

		#endregion

		#region SetValue, ClearValue, SetValueParts

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();
			lo_dp.AddProperty("Seq", typeof(string), lbl_pk.Text);	//순번
			lo_dp.AddProperty("Training_Id", typeof(string), lbl_training_id.Text);	//운동ID
			lo_dp.AddProperty("Training_Dt", typeof(string), txt_training_dt.Text);	//운동일
			lo_dp.AddProperty("Start_Hour", typeof(string), ddl_start_hour.SelectedValue);	//시작시
			lo_dp.AddProperty("Start_Minute", typeof(string), ddl_start_minute.SelectedValue);	//시작분
			lo_dp.AddProperty("End_Hour", typeof(string), ddl_end_hour.SelectedValue);	//종료시
			lo_dp.AddProperty("End_Minute", typeof(string), ddl_end_minute.SelectedValue);	//종료분
			lo_dp.AddProperty("Location", typeof(string), ConversionUtil.DefaultValue(txt_location.Text));	//장소
			lo_dp.AddProperty("Create_User", typeof(string), USER_ID);	//최초등록자
			lo_dp.AddProperty("Create_Dt", typeof(string), "");	//최초등록일
			lo_dp.AddProperty("Update_User", typeof(string), USER_ID);	//최종수정자
			lo_dp.AddProperty("Update_Dt", typeof(string), "");	//최종수정일

			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value = "";
			ce_training_dt.SelectedDate = DateTime.Now.AddDays(0);
			ddl_start_hour.SelectedIndex = 0;
			ddl_start_minute.SelectedIndex = 0;
			ddl_end_hour.SelectedIndex = 0;
			ddl_end_minute.SelectedIndex = 0;
			txt_location.Text = "";
			ltr_calc_action_weight.Text = "0";
			ltr_calc_action_count.Text = "0";
			ltr_calc_set_count.Text = "0";
			ibtn_move.Visible = false;

			SetNewTrainingId();
		}

		//부품 - xml로 저장 및 수정
		private string SetValueParts()
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			//루프를 돌면서 선택된 데이터만 XML로 만듬
			for (int i = 0; i < gv_parts.Rows.Count; i++)
			{
				CheckBox cb_select = (CheckBox)gv_parts.Rows[i].FindControl("cb_select");
				string ls_seq = gv_parts.DataKeys[i].Values["Seq"].ToString();
				string training_type_id = gv_parts.DataKeys[i].Values["Training_Type_Id"].ToString();
				TextBox txt_action_weight = (TextBox)gv_parts.Rows[i].FindControl("txt_action_weight");
				TextBox txt_action_count = (TextBox)gv_parts.Rows[i].FindControl("txt_action_count");
				TextBox txt_set_count = (TextBox)gv_parts.Rows[i].FindControl("txt_set_count");
				TextBox txt_remark = (TextBox)gv_parts.Rows[i].FindControl("txt_remark");
				string ls_save_yn = gv_parts.DataKeys[i].Values["Save_Yn"].ToString();

				if (lbl_pk.Text == "")
				{
					ls_seq = "0";
				}

				if (cb_select.Checked)
				{
					sb.Append("<UPDMS_FIT_WEIGHT_TRAINING_PARTS>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("<Save_Yn>" + ls_save_yn + "</Save_Yn>");	//실제 저장되는 값은 아님
					sb.Append("<Training_Id>" + lbl_training_id.Text + "</Training_Id>");
					sb.Append("<Training_Type_Id>" + training_type_id + "</Training_Type_Id>");
					sb.Append("<Action_Weight>" + ConversionUtil.DefaultValue(txt_action_weight.Text, "0.0") + "</Action_Weight>");
					sb.Append("<Action_Count>" + ConversionUtil.DefaultValue(txt_action_count.Text, "0") + "</Action_Count>");
					sb.Append("<Set_Count>" + ConversionUtil.DefaultValue(txt_set_count.Text, "0") + "</Set_Count>");
					sb.Append("<Remark>" + ConversionUtil.DefaultValue(txt_remark.Text) + "</Remark>");
					sb.Append("<Create_User>" + USER_ID + "</Create_User>");
					sb.Append("<Create_Dt></Create_Dt>");
					sb.Append("<Update_User>" + USER_ID + "</Update_User>");
					sb.Append("<Update_Dt></Update_Dt>");
					sb.Append("</UPDMS_FIT_WEIGHT_TRAINING_PARTS>");
				}
			}

			sb.Append("</UPDMS>");

			return sb.ToString();
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				//접근권한 체크
				if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
				{
					Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
				}
				//사용권한별 버튼처리
				PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
			}
			ChangePageMode();

			//페이지모드 처리
			string ls_class = String.IsNullOrEmpty(lbl_pk.Text) ? "sbtn sbtn_mode_i" : "sbtn sbtn_mode_u";
			string ls_title = String.IsNullOrEmpty(lbl_pk.Text) ? "입력" : "수정";
			btn_chg_mode.Attributes.Add("class", ls_class);
			btn_chg_mode.Attributes.Add("title", ls_title);
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":		// 처음 페이지로드시
					Top.Visible = true;
					menu_area.Attributes.Add("class", "");
					ibtn_delete.Visible = access.CheckPgmUsingGrant(USER_DIV, PID);
					ibtn_close.Visible = false;
					break;
				case "P":	// 팝업으로 열때
					Top.Visible = false;
					menu_area.Attributes.Add("class", "nodisplay");
					ibtn_delete.Visible = false;
					ibtn_close.Visible = true;

					if (!string.IsNullOrEmpty(gs_training_dt))
					{
						ce_training_dt.SelectedDate = Convert.ToDateTime(gs_training_dt);
					}
					break;
			}
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text = cb_list_all.Checked
					? (li_row_count - e.Row.RowIndex).ToString()
					: ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();

				//당일표기(요일)
				string training_dt = e.Row.Cells[4].Text.ToString();
				
				//오늘이면
				if (DateUtil.GetDiffDay(DateUtil.GetNow("yyyy-MM-dd"), training_dt) == 0)
				{
					e.Row.Cells[5].Attributes.Add("class", "color_darkred b");
				}
				//오늘이후이면
				else if (DateUtil.GetDiffDay(DateUtil.GetNow("yyyy-MM-dd"), training_dt) > 0)
				{
					e.Row.Cells[5].Attributes.Add("class", "color_darkgreen b");
				}

				//페이지별 합계
				ld_total_weight += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total_Weight"));
				ld_total_count += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total_Count"));
				ld_total_set += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total_set"));
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[0].ColumnSpan = 7; //화면에 보이는것. Visible=false는 안보이는것 포함
				e.Row.Cells[1].Visible = false;
				e.Row.Cells[2].Visible = false;
				e.Row.Cells[3].Visible = false;
				e.Row.Cells[4].Visible = false;
				e.Row.Cells[5].Visible = false;
				e.Row.Cells[6].Visible = false;
				e.Row.Cells[7].Visible = false;
				e.Row.Cells[8].Visible = false;
				e.Row.Cells[9].Visible = false;
				e.Row.Cells[10].Visible = false;
				e.Row.Cells[11].Visible = false;
				e.Row.Cells[12].Visible = false;
				e.Row.Cells[13].Text = ld_total_weight.ToString("#,###,##0");
				e.Row.Cells[13].Attributes.Add("class", "money");
				e.Row.Cells[14].Text = ld_total_count.ToString("#,###,##0");
				e.Row.Cells[14].Attributes.Add("class", "money");
				e.Row.Cells[15].Text = ld_total_set.ToString("#,###,##0");
				e.Row.Cells[15].Attributes.Add("class", "money");
				e.Row.Cells[16].Text = "";
				e.Row.Cells[16].Attributes.Add("class", "none");
				e.Row.Cells[16].ColumnSpan = 2;
				e.Row.Cells[17].Visible = false;
			}
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();	//0.체크박스
			h_no.Value = row.Cells[1].Text.ToString();	//1.번호
			lbl_pk.Text = gv.DataKeys[row.RowIndex].Values["Seq"].ToString();	//2.Seq
			lbl_training_id.Text = lbtn_rc.Text;	//3.Training_Id
			txt_training_dt.Text = row.Cells[4].Text.ToString();	//4.Training_Dt(template)
			//5.Week_Day
			ddl_start_hour.SelectedValue = gv.DataKeys[row.RowIndex].Values["Start_Hour"].ToString();	//6.Start_Hour
			ddl_start_minute.SelectedValue = gv.DataKeys[row.RowIndex].Values["Start_Minute"].ToString();	//7.Start_Minute
			ddl_end_hour.SelectedValue = gv.DataKeys[row.RowIndex].Values["End_Hour"].ToString();	//8.End_Hour
			ddl_end_minute.SelectedValue = gv.DataKeys[row.RowIndex].Values["End_Minute"].ToString();	//9.End_Minute
			//10.Training_Time
			//11.Training_Part
			//12.Training_Part_Nm
			//13.Total_Weight
			//14.Total_Count
			//15.Total_Set
			txt_location.Text = row.Cells[16].Text.ToString();	//16.Location
			//17.Reslut

			CallJavaScriptMethodInAjax("toggleObj('div_detail');");
			SelectPartsProcess(lbl_training_id.Text, gv.DataKeys[row.RowIndex].Values["Training_Part"].ToString());
			SetCalcTotalTrainingResult();
			SetTrainingPartHeight();

			//팝업에서는 신규모드로 전환(수정은 없다)
			if (gs_page_mode == "P")
			{
				h_no.Value = "";
				lbl_pk.Text = "";
				ibtn_move.Visible = false;
				SetNewTrainingId();
			}
			else
			{
				SetChangeBtn();
			}
		}

		//RowDataBound
		protected void gv_parts_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);
			}

			//머지
			SMGridView sGv = new SMGridView(this.Page, ref gv_parts);
			sGv.RowSpanGridView(gv_parts, 4); //Training_Part_Nm
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			//운동종류별 입력값 먼저 저장
			InsertPartsProcess();

			if (global.CheckSaveMode("UPDMS_FIT_WEIGHT_TRAINING", "Seq", lbl_pk.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}

			//전체보기 해제
			cb_part_list_all.Checked = false;
			SetTrainingPartHeight();
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
					sb.Append("<UPDMS_FIT_WEIGHT_TRAINING>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_FIT_WEIGHT_TRAINING>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_training_dt_from", typeof(string), kw1);
			lo_dp.AddProperty("ls_training_dt_to", typeof(string), kw2);
			lo_dp.AddProperty("ls_training_part", typeof(string), kw3);
			lo_dp.AddProperty("ls_training_type_id", typeof(string), kw4);
			lo_dp.AddProperty("ls_location", typeof(string), kw5);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Fit1011m_NT _Fit1011m_NT = new Fit1011m_NT())
			{
				li_row_count = _Fit1011m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);
			
				lo_ds.Merge(_Fit1011m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//디테일 초기화
		protected void lbtn_init_detail_Click(object sender, EventArgs e)
		{
			ClearValue();
			SelectPartsProcess("", "");
		}

		//페이지모드변경
		protected void lbtn_chg_mode_Click(object sender, EventArgs e)
		{
			h_no.Value = "";
			lbl_pk.Text = "";
			ibtn_move.Visible = false;
			SetNewTrainingId();
		}

		//운동결과에서 체크박스(S) 선택시
		protected void cb_select_CheckedChanged(object sender, EventArgs e)
		{
			//선택한 Row를 활성/비활성 한다.
			GridViewRow gvr = ((GridViewRow)((Control)sender).Parent.Parent);
			int checked_row_index = gvr.RowIndex;

			CheckBox cb_select = (CheckBox)gv_parts.Rows[checked_row_index].FindControl("cb_select");
			TextBox txt_action_weight = (TextBox)gv_parts.Rows[checked_row_index].FindControl("txt_action_weight");
			TextBox txt_action_count = (TextBox)gv_parts.Rows[checked_row_index].FindControl("txt_action_count");
			TextBox txt_set_count = (TextBox)gv_parts.Rows[checked_row_index].FindControl("txt_set_count");
			TextBox txt_remark = (TextBox)gv_parts.Rows[checked_row_index].FindControl("txt_remark");
			CheckBox cb_remark = (CheckBox)gv_parts.Rows[checked_row_index].FindControl("cb_remark");

			if (cb_select.Checked)
			{
				txt_action_weight.Enabled = true;
				txt_action_count.Enabled = true;
				txt_set_count.Enabled = true;
				txt_remark.Enabled = true;
				cb_remark.Enabled = true;

				//어트리뷰트 추가
				string ls_attr_action_weight = "document.form1." + txt_action_weight.UniqueID + ".value=extractNumberDot(document.form1." + txt_action_weight.UniqueID + ".value);";
				string ls_attr_action_count = "document.form1." + txt_action_count.UniqueID + ".value=extractNumber(document.form1." + txt_action_count.UniqueID + ".value);";
				string ls_attr_set_count = "document.form1." + txt_set_count.UniqueID + ".value=extractNumber(document.form1." + txt_set_count.UniqueID + ".value);";
				txt_action_weight.Attributes.Add("onkeyup", ls_attr_action_weight);
				txt_action_count.Attributes.Add("onkeyup", ls_attr_action_count);
				txt_set_count.Attributes.Add("onkeyup", ls_attr_set_count);
				cb_remark.Attributes.Add("onclick", "extendRemark(\"" + txt_remark.ClientID + "\", \"" + cb_remark.ClientID + "\");");

				//td를 돌면서 class 추가
				for (int j = 0; j < gv_parts.Rows[checked_row_index].Cells.Count; j++)
				{
					gv_parts.Rows[checked_row_index].Cells[j].Attributes.Add("class", "bg_white");
				}
			}
			else
			{
				txt_action_weight.Text = "";
				txt_action_count.Text = "";
				txt_set_count.Text = "";
				txt_remark.Text = "";

				txt_action_weight.Enabled = false;
				txt_action_count.Enabled = false;
				txt_set_count.Enabled = false;
				txt_remark.Enabled = false;
				cb_remark.Enabled = false;
				cb_remark.Checked = false;

				//td를 돌면서 어트리뷰트 추가
				for (int j = 0; j < gv_parts.Rows[checked_row_index].Cells.Count; j++)
				{
					gv_parts.Rows[checked_row_index].Cells[j].Attributes.Add("class", "bg_gray");
				}
			}

			//비고높이 재설정
			SetExtendRemark();
		}

		//운동종류 체크박스 클릭시
		protected void cbl_training_part_SelectedIndexChanged(object sender, EventArgs e)
		{
			SetTrainingPart(lbl_training_id.Text);
			SetTrainingPartHeight();
		}

		//합계계산
		protected void lbtn_calc_total_Click(object sender, EventArgs e)
		{
			SetCalcTotalTrainingResult();
			SetExtendRemark();
		}

		//운동결과 모두보기
		protected void cb_part_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SetTrainingPartHeight();
			SetExtendRemark();
		}

		#endregion
	}
}